package com.zjcode.cdcer.controller;

import static com.zjcode.cdcer.config.MConsts.SUB_DETAIL;

import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.component.commons.controller.BaseController;
import com.chinatechstar.component.commons.supports.PageData;
import com.zjcode.cdcer.config.MConsts;
import com.zjcode.cdcer.config.MConsts.Common;
import com.zjcode.cdcer.enums.CommonEnum;
import com.zjcode.cdcer.model.CerTablefieldShowstatus;
import com.zjcode.cdcer.model.TkmSysteminitImportInfo;
import com.zjcode.cdcer.model.basic.JsonObj;
import com.zjcode.cdcer.model.CerEndoscopicDiagnosisDetails;
import com.zjcode.cdcer.service.CerEndoscopicDiagnosisDetailsService;
import com.zjcode.cdcer.service.CerTablefieldShowstatusService;
import com.zjcode.cdcer.service.TkmSysteminitImportInfoService;
import com.zjcode.cdcer.utils.Utils;
import io.swagger.annotations.ApiOperation;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName:SystemInitController
 * @功能：初始数据上报
 * @author：wlei
 * @日期：2022/7/9-02:00
 **/
@RestController
@Slf4j
@RequestMapping("/v1/initialdatareporting/")
public class InitialDataReportingController extends BaseController {

    @Autowired
    private CerTablefieldShowstatusService cerTablefieldShowstatusService;
    @Autowired
    private TkmSysteminitImportInfoService systeminitImportInfoService;
    @Autowired
    private CerEndoscopicDiagnosisDetailsService cerEndoscopicDiagnosisDetailsService;

    /**
     * 返回所有可以用于显示的表字段信息
     *
     * @return
     */
    @GetMapping("listAllTableColumn")
    public JsonObj listAllTableColumn(HttpServletRequest request) {
        PageData pageData = getPageData();
        List<CerTablefieldShowstatus> colums = cerTablefieldShowstatusService.selectAllTableColumnBy(
            "import01");

        Map<String, Object> data = new HashMap<>();
        data.put("colums", colums);

        return JsonObj.success(data);
    }

    /**
     * 返回所有可以用于显示的表字段信息
     *
     * @param request
     * @return
     */
    @GetMapping("listAllTableColumn4Office")
    public JsonObj listAllTableColumn4Office(HttpServletRequest request) {
        PageData pageData = getPageData();

        List<CerTablefieldShowstatus> colums = cerTablefieldShowstatusService.selectAllTableColumnBy(
            "import02");

        Map<String, Object> data = new HashMap<>();
        data.put("colums", colums);

        return JsonObj.success(data);
    }

    /**
     * 删除数据
     *
     * @param pageData
     * @return
     */
    @PostMapping("deleteById")
    @ApiOperation("获取所有的初始数据信息列表")
    public JsonObj deleteById(@RequestBody PageData pageData) {
        String id = (String) pageData.get("id");
        int i = systeminitImportInfoService.deleteById(id);
        if (i > 0) {
            return JsonObj.success("删除成功");
        } else {
            return JsonObj.error("删除失败");
        }
    }

    @GetMapping("findRecord")
    @ApiOperation("获取所有的初始数据信息列表")
    public JsonObj findRecord() {
        PageData pageData = getPageData();
        String id = (String) pageData.get("id");
        TkmSysteminitImportInfo info = systeminitImportInfoService.findById(id);
        List<CerEndoscopicDiagnosisDetails> list = cerEndoscopicDiagnosisDetailsService.findByParentId(
            id);
        if (info != null) {
            String extFlag2 = info.getExtFlag2();
            Map<String, Boolean> map = Utils.parseExtFlag2(extFlag2);
            info.setIsShowSgDetail(map.get(SUB_DETAIL.SG) ? 1 : 0);
            info.setIsShowBmDetail(map.get(SUB_DETAIL.BM) ? 1 : 0);
            info.setIsShowWDetail(map.get(SUB_DETAIL.WD) ? 1 : 0);
            info.setReportFilePath("");
            info.setBlReportFilePath("");

            Map<String, Object> data = new HashMap<>();
            Map<String, List<CerEndoscopicDiagnosisDetails>> detailMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(list)) {
                detailMap = list
                    .parallelStream()
                    .collect(Collectors.groupingBy(CerEndoscopicDiagnosisDetails::getObjType));
            }
            data.put(CommonEnum.RESP.getValue(), info);
            data.put("detailMap", detailMap);
            return JsonObj.success(data);
        } else {
            return JsonObj.error("未能获取到对应的数据");
        }
    }

    /**
     * 更新数据
     *
     * @param pageData
     * @return
     */
    @PostMapping("updateRecord")
    @ApiOperation("更新数据")
    public JsonObj updateRecord(@RequestBody PageData pageData) {

        String json = JSONObject.toJSONString(pageData);
        String tmp = (String) pageData.get(MConsts.Common.SKIP);
        // 是否需要跳过出错提醒
        boolean skip = "1".equals(tmp);

        TkmSysteminitImportInfo info = JSONObject.parseObject(json, TkmSysteminitImportInfo.class);

        // 进行数据验证
        List<String> errors = Utils.validateSysteminitImportInfoData(info);
        if (errors.size() > 0 && !skip) {
            return JsonObj.error(errors
                                     .stream()
                                     .collect(Collectors.joining(Common.DELIMITER_CHARACTER)));
        }

        info.setErrorMessage(errors
                                 .stream()
                                 .collect(Collectors.joining(MConsts.Common.DELIMITER_CHARACTER)));

        String user = (String) pageData.get(Common.USER);

        // 取出原始数据
        TkmSysteminitImportInfo original = systeminitImportInfoService.findById(info.getId());
        // 登录用户必须是创建人才能修改数据
        if (!original
            .getCreateBy()
            .equals(user)) {
            return JsonObj.error("您无法修改当前记录");
        }

        ////内镜诊断详情数据集合
        //List<CerEndoscopicDiagnosisDetails> list = new ArrayList<>();
        //
        ////得到食管集合数据(sg)
        //Object sg = pageData.get(SUB_DETAIL.ESOPHAGUS);
        ////得到贲门数据(bm)
        //Object bm = pageData.get(SUB_DETAIL.CARDIA);
        ////得到胃集合数据(w)
        //Object w = pageData.get(SUB_DETAIL.STOMACH);
        //
        ////报告单存放地址
        //Object reportFilePath = pageData.get(URL.REPORT_PATH);
        ////报告单url访问地址
        //Object reportFileUrl = pageData.get(URL.REPORT_URL);
        ////病理报告单存放地址
        //Object blReportFilePath = pageData.get(URL.PATHOLOGY_PATH);
        ////病理报告单url访问地址
        //Object blReportFileUrl = pageData.get(URL.PATHOLOGY_URL);
        //
        //if (ObjectUtils.isNotEmpty(sg)) {
        //    List<CerEndoscopicDiagnosisDetails> sgList = handleEndoscopicDiagnosisDetails(sg,
        //                                                                                  ENDOSCOPIC_DIAGNOSIS_TYPE.SG,
        //                                                                                  info.getId(),
        //                                                                                  original.getCreateBy());
        //    List<String> errores = Utils.validateSgData(sgList);
        //    if (errores.size() > 0) {
        //        return JsonObj.error(errores
        //                                 .stream()
        //                                 .collect(Collectors.joining(Common.DELIMITER_CHARACTER)));
        //    }
        //    list.addAll(sgList);
        //}
        //
        //if (ObjectUtils.isNotEmpty(bm)) {
        //    List<CerEndoscopicDiagnosisDetails> bmList = handleEndoscopicDiagnosisDetails(bm,
        //                                                                                  ENDOSCOPIC_DIAGNOSIS_TYPE.BM,
        //                                                                                  info.getId(),
        //                                                                                  original.getCreateBy());
        //    List<String> errores = Utils.validateBmData(bmList);
        //    if (errores.size() > 0) {
        //        return JsonObj.error(errores
        //                                 .stream()
        //                                 .collect(Collectors.joining(Common.DELIMITER_CHARACTER)));
        //    }
        //    list.addAll(bmList);
        //}
        //
        //if (ObjectUtils.isNotEmpty(w)) {
        //    List<CerEndoscopicDiagnosisDetails> wList = handleEndoscopicDiagnosisDetails(w,
        //                                                                                 ENDOSCOPIC_DIAGNOSIS_TYPE.WD,
        //                                                                                 info.getId(),
        //                                                                                 original.getCreateBy());
        //    List<String> errores = Utils.validateWData(wList);
        //    if (errores.size() > 0) {
        //        return JsonObj.error(errores
        //                                 .stream()
        //                                 .collect(Collectors.joining(Common.DELIMITER_CHARACTER)));
        //    }
        //    list.addAll(wList);
        //}

        // 重新赋值原始数据
        updateOriginal(info, original);

        //if (Objects.nonNull(reportFilePath)) {
        //    original.setReportFilePath(reportFilePath.toString());
        //}
        //
        //if (Objects.nonNull(reportFileUrl)) {
        //    original.setReportFileUrl(reportFileUrl.toString());
        //}
        //
        //if (Objects.nonNull(blReportFilePath)) {
        //    original.setBlReportFilePath(blReportFilePath.toString());
        //}
        //
        //if (Objects.nonNull(blReportFileUrl)) {
        //    original.setBlReportFileUrl(blReportFileUrl.toString());
        //}

        // 执行数据库的更新

        // 更新主表数据
        int updateResult = systeminitImportInfoService.updateRecord(original);
        // 删除旧的子表数据
        //cerEndoscopicDiagnosisDetailsService.deleteByParentId(info.getId());
        // 插入新的子表数据
        //cerEndoscopicDiagnosisDetailsService.batchInsert(list);

        if (updateResult > 0) {
            return JsonObj.success("更新成功");
        } else {
            return JsonObj.error("更新失败");
        }

    }

    /**
     * 重新赋值原始数据
     *
     * @param info
     * @param original
     */
    private void updateOriginal(TkmSysteminitImportInfo info, TkmSysteminitImportInfo original) {
        original.setMzh(info.getMzh());
        original.setZyh(info.getZyh());
        original.setName(info.getName());
        original.setSex(info.getSex());
        original.setAge(info.getAge());
        original.setPhone(info.getPhone());
        original.setSfz(info.getSfz());
        original.setAddr(info.getAddr());
        original.setNjzlTime(info.getNjzlTime());
        original.setZldxLy(info.getZldxLy());
        original.setNjNum(info.getNjNum());
        original.setAche(info.getAche());
        original.setDye(info.getDye());
        original.setIsHj(info.getIsHj());
        original.setHp(info.getHp());
        original.setHpjcjg(info.getHpjcjg());
        original.setPicNums(info.getPicNums());
        original.setNjStaff(info.getNjStaff());
        original.setVerifyStaff(info.getVerifyStaff());
        original.setNjzd(info.getNjzd());
        original.setBlNum(info.getBlNum());
        original.setBlbgTime(info.getBlbgTime());
        original.setSgblCode(info.getSgblCode());
        original.setBmblCode(info.getBmblCode());
        original.setWblCode(info.getWblCode());
        original.setSezcCode(info.getSezcCode());
        original.setBlzdStaff(info.getBlzdStaff());
        original.setBlshStaff(info.getBlshStaff());
        original.setBlzd(info.getBlzd());
        original.setIsHaveError(
            info.getErrorMessage() == null || "".equals(info.getErrorMessage()) ? 0 : 1);
        original.setErrorMessage(info.getErrorMessage() == null ? "" : info.getErrorMessage());
        original.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
    }


    public List<CerEndoscopicDiagnosisDetails> handleEndoscopicDiagnosisDetails(Object obj,
                                                                                String type,
                                                                                String id,
                                                                                String createBy) {
        //转换数据
        String str = obj.toString();
        List<CerEndoscopicDiagnosisDetails> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(str)) {
            int index = 0;
            list = JSONObject.parseArray(str, CerEndoscopicDiagnosisDetails.class);
            list
                .parallelStream()
                .forEach(item -> {
                    //主键
                    item.setId(get32UUID());
                    //关联主键
                    item.setParentId(id);
                    //类型
                    item.setObjType(type);
                    //删除参数
                    item.setDeleted(0);
                    //版本
                    item.setVersion(1);
                    //创建者
                    item.setCreateBy(createBy);
                    //排序
                    item.setSort(String.valueOf(index + 1));
                });
        }
        return list;
    }
}
